package de.bmuskalla.brainfuck;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;

public class BFDebuggerListener implements Runnable {

	private boolean stop = false;
	private BFInterpreter interpreter;

	public BFInterpreter getInterpreter() {
		return interpreter;
	}

	public void setInterpreter(BFInterpreter interpreter) {
		this.interpreter = interpreter;
	}

	public void run() {
		try {
			runDebugger();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void runDebugger() throws IOException {
		ServerSocket server = new ServerSocket(6670);
		Socket accept = server.accept();
		BufferedReader buf = null;
		buf = new BufferedReader(new InputStreamReader(accept.getInputStream()));
		PrintStream output = null;
		output = new PrintStream(accept.getOutputStream());
		String command = "";

		while (!stop) {
			command = buf.readLine();
			if (command.equals("exit")) {
				stop = true;
			} else if (command.equals("resume")) {
				interpreter.resume();
			} else if (command.startsWith("addBreakpoint")) {
				int line = Integer.parseInt(command.substring(command
						.indexOf(":") + 1));
				interpreter.addBreakpoint(line);
			} else if (command.startsWith("removeBreakpoint")) {
				int line = Integer.parseInt(command.substring(command
						.indexOf(":") + 1));
				interpreter.addBreakpoint(line);
			} else if (command.startsWith("stack")) {
				final String[] stack = interpreter.getStack();
				String controlStack = "";
				for (int i = 0; i < stack.length; i++) {
					String frame = stack[i];
					if (frame != null) {
						controlStack += frame + ":" + i + "#";
					}
				}
				output.println(controlStack);
			} else {
				output.append("Unrecognized command!");
			}
		}
	}
}
